﻿using FieldTools.Client.Command;
using Microsoft.Web.WebView2.Wpf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
using System.IO;
using System.Windows;
using System.Text.RegularExpressions;
using FieldTools.Client.Model.Window;
using FieldTools.Util;
using FieldTools.Client.Tools;
using FieldTools.Client.Business.IBusiness;

namespace FieldTools.Client.ViewModel.Window
{
    /// <summary>
    /// 
    /// </summary>
    public class XMLViewModel : NotificationObject, ISingletonDependency
    {
        private readonly IXMLBus _xMLBus;
        public XMLViewModel(IXMLBus iXMLBus)
        {
            _xMLBus = iXMLBus;
            //LogHelper.WriteLog("打开xml工具");
            obj = CacheHelper.GetOrSetCache("XMLModel", new XMLModel()
            {
                Url = "https://blog.csdn.net/weixin_42378387",
                Path = "//body",
                Type = 1,
                SourceType = 1,
                PathMode = 1
            });

            //获取源码
            GetHtmlDoc();
        }

        #region 实体
        HtmlDocument? html = null;
        XMLModel? obj = null;
        /// <summary>
        /// url
        /// </summary>
        public string? Url
        {
            get { return obj.Url; }
            set { obj.Url = value; CacheHelper.SetCache("XMLModel", obj); this.RaisePropertyChanged(nameof(Url)); }
        }

        /// <summary>
        /// 节点路径
        /// </summary>
        public string? Path
        {
            get { return obj.Path; }
            set { obj.Path = value; CacheHelper.SetCache("XMLModel", obj); this.RaisePropertyChanged(nameof(Path)); }
        }

        private string? sourceDoc;
        /// <summary>
        /// 源码
        /// </summary>
        public string? SourceDoc
        {
            get { return sourceDoc; }
            set { sourceDoc = value; this.RaisePropertyChanged(nameof(SourceDoc)); }
        }

        private string? showDoc;
        /// <summary>
        /// 抓取的源码
        /// </summary>
        public string? ShowDoc
        {
            get { return showDoc; }
            set { showDoc = value; this.RaisePropertyChanged(nameof(ShowDoc)); }
        }

        /// <summary>
        /// 读取类型，1 InnerHtml,2 OuterHtml,3 InnerText
        /// </summary>
        public int? Type
        {
            get { return obj.Type; }
            set { obj.Type = value; CacheHelper.SetCache("XMLModel", obj); this.RaisePropertyChanged(nameof(Type)); }
        }

        /// <summary>
        /// 源码获取类型,1 url, 2 网页
        /// </summary>
        public int? SourceType
        {
            get { return obj.SourceType; }
            set { obj.SourceType = value; CacheHelper.SetCache("XMLModel", obj); this.RaisePropertyChanged(nameof(SourceType)); }
        }

        /// <summary>
        /// 抓取路径类型,1 xpath, 2 selectors
        /// </summary>
        public int? PathMode
        {
            get { return obj.PathMode; }
            set { obj.PathMode = value; CacheHelper.SetCache("XMLModel", obj); this.RaisePropertyChanged(nameof(PathMode)); }
        }

        /// <summary>
        /// 属性
        /// </summary>
        public string? Attributes
        {
            get { return obj.Attributes; }
            set { obj.Attributes = value; CacheHelper.SetCache("XMLModel", obj); this.RaisePropertyChanged(nameof(Attributes)); }
        }


        #endregion

        #region 事件
        private BaseCommand execute;
        /// <summary>
        /// 执行事件
        /// </summary>
        public BaseCommand Execute
        {
            get
            {
                if (execute == null)
                {
                    execute = new BaseCommand(new Action<object>(o =>
                    {
                        ShowDoc = _xMLBus.Crawl(SourceDoc, (int)PathMode, Path, (int)Type, Attributes);
                    }));
                }
                return execute;
            }
        }
        private BaseCommand goToUrl;
        /// <summary>
        /// 访问网页
        /// </summary>
        public BaseCommand GoToUrl
        {
            get
            {
                if (goToUrl == null)
                {
                    goToUrl = new BaseCommand(new Action<object>(async o =>
                    {
                        //打开网页
                        await OpenWeb(o);
                        //获取源码
                        //GetHtmlDoc();

                    }));
                }
                return goToUrl;
            }
        }
        #endregion

        #region 方法
        /// <summary>
        /// 打开网页
        /// </summary>
        /// <param name="o"></param>
        private async Task OpenWeb(object? o)
        {
            if (o == null)
                return;
            object[]? multiObj = o as object[];
            if (multiObj?[0] is WebView2 webView && webView.CoreWebView2 != null)
            {
                webView.CoreWebView2.Navigate(Url);
                if (SourceType == 2)
                {
                    string doc = await webView.CoreWebView2.ExecuteScriptAsync("document.documentElement.outerHTML;");
                    doc = (Regex.Unescape(doc)).Remove(0,1);
                    SourceDoc = FormatXml(doc.Remove(doc.Length-1,1));
                }
                //SourceDoc = webView.CoreWebView2.;
                //sourceDoc = Regex.Escape(sourceDoc);
            }
        }
        /// <summary>
        /// 获取源码
        /// </summary>
        private void GetHtmlDoc()
        {
            if(SourceType==1 && Url != null && Url != "")
            {
                html = XmlHelper.GetHtmlByHtmlWeb(Url);

                if (html != null)
                {
                    //SourceDoc = html.Text;
                    //SourceDoc = html.DocumentNode.OuterHtml;
                    SourceDoc = FormatXml(html.DocumentNode.OuterHtml);
                }
            }
        }
        /// <summary>
        /// 爬取执行
        /// </summary>
        //private void Crawl()
        //{
        //    ShowDoc = "";
        //    if (PathMode == 1 && html != null)
        //    {
        //        HtmlDocument doc = new HtmlDocument();
        //        doc.LoadHtml(SourceDoc);
        //        var nodes = XmlHelper.GetHtmlNodes(doc, Path);
        //        if (nodes == null)
        //        {
        //            MessageBox.Show("未查询到节点");
        //            return;
        //        }
        //        foreach (var node in nodes)
        //        {
        //            string text = "";
        //            switch (Type)
        //            {
        //                case 1: text = node.OuterHtml; break;
        //                case 2: text = node.InnerHtml; break;
        //                case 3: text = node.InnerText; break;
        //                default: break;
        //            }
        //            if (Attributes != null && Attributes != "")
        //            {
        //                ShowDoc += node.Attributes[Attributes].Value + "\r\n";
        //            }
        //            else
        //            {
        //                ShowDoc += text + "\r\n";
        //            }
        //        }
        //    }
        //    else if (PathMode == 2 && SourceDoc != "")
        //    {
        //        var ss = XmlHelper.GetElementsByAngleSharp(SourceDoc, Path);
        //        if (ss == null)
        //        {
        //            MessageBox.Show("未查询到节点");
        //            return;
        //        }
        //        foreach (var e in ss)
        //        {
        //            string text = "";
        //            switch (Type)
        //            {
        //                case 1: text = e.OuterHtml; break;
        //                case 2: text = e.InnerHtml; break;
        //                case 3: text = e.TextContent; break;
        //                default: break;
        //            }
        //            if (Attributes != null && Attributes != "")
        //            {
        //                try
        //                {
        //                    ShowDoc += e.Attributes[Attributes]?.Value + "\r\n";
        //                }
        //                catch (Exception ex)
        //                {
        //                    ShowDoc += ex.Message + "\r\n";
        //                }
        //            }
        //            else
        //            {
        //                ShowDoc += text + "\r\n";
        //            }
        //        }
        //    }
        //}

        private static string FormatXml(string xml)
        {
            //System.Xml.XmlDocument doc = new();
            //doc.LoadXml(xml);

            //System.IO.StringWriter sw = new();
            //using (System.Xml.XmlTextWriter writer = new(sw))
            //{
            //    writer.Indentation = 2;  // the Indentation
            //    writer.Formatting = System.Xml.Formatting.Indented;
            //    doc.WriteContentTo(writer);
            //    writer.Close();
            //}
            //return sw.ToString();
            return xml.Replace("/>", "/>\r\n").Replace("><", ">\r\n<");
        }


        #endregion
    }
}
